import { drawerConfig, drawerTitle, drawerVisible } from "./drawer";
import { searchConfig } from "./search";
import { tableData, tableConfig, tablePage, tableLoading } from "./table";
import { modalConfig, modalTitle, modalVisible } from "./modal";
import {
  merchantOptions,
  operateType,
  tmpMerchantOptions,
  queryParams,
  tableActiveKey,
  isDisplay,
  withdrawRuleForm,
  agreeLoading,
  winRef,
  searchList,
  tabPower,
  defaultSearchList,
  defaultModalFormState,
  drawerFormState,
} from "./store";
import { calcWrapHeight, fetchSearchMap } from "./utils";
import WithdrawRules from "./components/withdrawRules";
import { WindowResizeChange } from "@/utils/tools";
import { isHasPower } from "@/assets/directives/tools";
import { handleSearchTime } from "@userList/search";
const defineApiMap = new Map([
  [0, () => withdrawApi.queryWithdrawList(queryParams)],
  [1, () => withdrawRuleApi.query()],
]);
const handleFetchListTask = async (number) => {
  const api: any = defineApiMap.get(number);
  const result: any = await api();
  if (result.code != 200) return message.error(result.message);
  if (number == 0) {
    tableData.value = result?.data?.data?.withdraw_list ?? [];
    tablePage.total = result?.data?.data?.attributes?.total ?? 0;
  }
  if (number === 1) {
    if (result.data) isDisplay.value = false;
    else isDisplay.value = true;
    initObjAttr(withdrawRuleForm, result.data);
    withdrawRuleForm.wallet_amount_limit = toThousands(
      withdrawRuleForm.wallet_amount_limit
    );
  }
};
export const fetchList = async () => {
  try {
    handleSearchTime(
      ["withdraw_time_start", "withdraw_time_end"],
      queryParams,
      "YYYY-MM-DD",
      "withdraw_time"
    );
    handleSearchTime(
      ["arrival_time_start", "arrival_time_end"],
      queryParams,
      "YYYY-MM-DD",
      "arrival_time"
    );
    tableData.value.length = 0;
    tableLoading.value = true;
    queryParams.page = tablePage.current;
    queryParams.page_size = tablePage.pageSize;
    await handleFetchListTask(tableActiveKey.value);
  } catch (error: any) {
    message.error(error.message);
  } finally {
    tableLoading.value = false;
  }
};
export const showDrawer = () => (drawerVisible.value = true);
export const showModal = () => (modalVisible.value = true);
export const handleAction = async ({ record, type }: any) => {
  try {
    operateType.value = type;
    switch (trimAll(type)) {
      case "view":
        showDrawer();
        drawerTitle.value = $t("base.withdrawOrderDetail");
        initObjAttr(drawerFormState, record, "origin");
        break;
      case "refuse":
        modalTitle.value = $t("base.refuseWithdraw");
        defaultModalFormState[tableActiveKey.value].withdraw_id = record.id;
        showModal();
        break;
      case "agree":
        modalTitle.value = $t("base.agreeWithdraw");
        tableLoading.value = true;
        agreeLoading.value = true;
        const res: any = await withdrawApi.queryWithdrawPlatform({
          withdraw_id: record.id,
        });
        defaultModalFormState[tableActiveKey.value].withdrawal_amount =
          res.data.withdrawal_amount;
        defaultModalFormState[tableActiveKey.value].withdraw_amount =
          res.data.withdraw_amount;
        defaultModalFormState[tableActiveKey.value].withdraw_id = record.id;
        merchantOptions.value = arrayToOptions(res.data.pay_platform_list, {
          label: "name",
          value: "id",
        });
        tmpMerchantOptions.value = res.data.pay_platform_list;
        showModal();
        break;
    }
  } catch (error: any) {
    message.error(error.message);
  } finally {
    if (operateType.value === "agree") {
      tableLoading.value = false;
      agreeLoading.value = false;
    }
  }
};
export const refreshTable = async (searchParams: any = {}) => {
  tablePage.current = 1;
  initObjAttr(queryParams, searchParams);
  await fetchList();
};
export let tmp_proxy: any = null;
export default defineComponent({
  setup(props, { attrs, emit, expose, slots }) {
    tabPower[0] = isHasPower("withdrawApi.queryWithdrawList");
    tabPower[1] = isHasPower("withdrawRuleApi.query");
    tableActiveKey.value = tabPower[0] ? 0 : tabPower[1] ? 1 : Infinity;
    searchList.value = defaultSearchList[tableActiveKey.value] ?? [];
    const { proxy } = reactive<any>(getCurrentInstance());
    tmp_proxy = proxy;
    const defineSearch = searchConfig();
    const defineDrawer = drawerConfig();
    const defineTable = tableConfig();
    const defineModal = modalConfig();
    watch(
      () => sysZone.value,
      () => fetchList()
    );
    onActivated(() => {
      fetchList();
      if (tableActiveKey.value === 0) {
        fetchSearchMap();
      } else {
        calcWrapHeight();
        winRef.value = new WindowResizeChange(calcWrapHeight, 300);
      }
    });
    onDeactivated(() => {
      removeEvent(
        window,
        "resize",
        winRef.value?.callback ?? (() => {}),
        false
      );
    });
    return () => (
      <>
        <s-search {...defineSearch} />
        {tableActiveKey.value === 0 ? (
          <>
            <s-table {...defineTable} />
            <s-drawer {...defineDrawer} />
            <s-modal {...defineModal} />
          </>
        ) : (
          <>
            <WithdrawRules />
          </>
        )}
      </>
    );
  },
});
